package com.cocostudio.erpapp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.ZoomDensity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import com.amo.demo.wheelview.NumericWheelAdapter;
import com.amo.demo.wheelview.OnWheelChangedListener;
import com.amo.demo.wheelview.WheelView;
import com.cocostudio.erpapp.common.Debug;
import com.cocostudio.erpapp.utils.Constant;
import com.cocostudio.erpapp.utils.WebServiceUtils;
import com.cocostudio.erpapp.vo.WSHistorySaleResult;
import com.cocostudio.erpapp.vo.WSRealTimeSalesResult;
import com.cocostudio.erpapp.web.CustomWebChromeClient;
import com.cocostudio.erpapp.R;

public class DeptHistorySalesActivity extends CustomFragmentActivity {
    private static final String TAG = "DeptHistorySalesActivity";
    private static View searchView;
    private Dialog dialog;
    private static int START_YEAR = 2010, END_YEAR = 2020;

    private WebView webView;
    private EditText search_startdate;
    private EditText search_enddate;
    private String showtype;
    
    private EditText search_product_name;
    private EditText search_product_size;
    private EditText search_dept_code;
    private EditText search_dept_level;
    private EditText search_product_code;
    
    private RadioGroup search_showtype;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (Debug.LOGD) {
            Log.d(TAG, "onCreate.");
        }
        super.onCreate(savedInstanceState);
        initView();
    

    }
    
    public void onStartDate(View view){
        
        showDatePicker("请选择开始日期",search_startdate);
    }
    
    public void onEndDate(View view){
        showDatePicker("请选择结束日期",search_enddate);
    }
    
    public void onSearchClicked(View view) {

        //StringWriter htmlcontent=new StringWriter();
        //组织网页内容
        try {
            //从接口获取信息
            pdg = ProgressDialog.show(DeptHistorySalesActivity.this, "温馨提示", "数据请求中，请稍后！");
            pdg.setCancelable(true);
            pdg.setCanceledOnTouchOutside(true);
      
            webView.loadUrl( Constant.urlprefix+ "dept_history_sales.html");

            
            pdg.dismiss();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
    
    }
    
    
    public String getFromAssets(String fileName){ 
        String Result="";
        try { 
             InputStreamReader inputReader = new InputStreamReader( getResources().getAssets().open(fileName) ); 
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line="";
             Result="";
            while((line = bufReader.readLine()) != null)
                Result += line;
        } catch (Exception e) { 
            e.printStackTrace(); 
        }
        return Result;
    } 
    
    private void initView() {
        this.showtype = "1";

        setContentView(R.layout.activity_dept_history_sales);
        
        setTitle(R.string.title_dept_history_sale); 
        
        setLeftButtonDrawable(R.drawable.btn_home);

        searchView = findViewById(R.id.search_component);   
        
        webView = (WebView) findViewById(R.id.detail_result_webview);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setSupportZoom(false);
        webView.setFocusableInTouchMode(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient( new CustomWebChromeClient());

        webView.addJavascriptInterface(this, "android");
        
        
        
        search_dept_code= (EditText)findViewById(R.id.search_dept_code);
        search_startdate= (EditText)findViewById(R.id.search_startdate);
        search_enddate = (EditText)findViewById(R.id.search_enddate);
        search_dept_level = (EditText)findViewById(R.id.search_dept_level);
        search_showtype = (RadioGroup)findViewById(R.id.showtype_radiogroup);
        
        
        
        search_showtype.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                    
                int btnid = group.getCheckedRadioButtonId();
                switch (btnid) {
                case R.id.showtype1:
                   DeptHistorySalesActivity.this.showtype="1";
                    break;
                case R.id.showtype2:
                   DeptHistorySalesActivity.this.showtype="2";
                    break;
                case R.id.showtype3:
                   DeptHistorySalesActivity.this.showtype="3";
                    break;
                default:
                    break;
                }
            }
        });
        
        search_dept_code.setText("010101");
        search_startdate.setText("2013-10-10");
        //search_enddate.setText("2013.11.22");
        
   }

    
    private void showDatePicker(String title,final EditText edittext){
        

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        // 添加大小月月份并将其转换为list,方便之后的判断
        String[] months_big = { "1", "3", "5", "7", "8", "10", "12" };
        String[] months_little = { "4", "6", "9", "11" };

        final List<String> list_big = Arrays.asList(months_big);
        final List<String> list_little = Arrays.asList(months_little);

        dialog = new Dialog(this);
        dialog.setTitle(title);
        // 找到dialog的布局文件
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.time_layout, null);

        // 年
        final WheelView wv_year = (WheelView) view.findViewById(R.id.year);
        wv_year.setAdapter(new NumericWheelAdapter(START_YEAR, END_YEAR));// 设置"年"的显示数据
        wv_year.setCyclic(true);// 可循环滚动
        wv_year.setLabel("年");// 添加文字
        wv_year.setCurrentItem(year - START_YEAR);// 初始化时显示的数据

        // 月
        final WheelView wv_month = (WheelView) view.findViewById(R.id.month);
        wv_month.setAdapter(new NumericWheelAdapter(1, 12));
        wv_month.setCyclic(true);
        wv_month.setLabel("月");
        wv_month.setCurrentItem(month);

        // 日
        final WheelView wv_day = (WheelView) view.findViewById(R.id.day);
        wv_day.setCyclic(true);
        // 判断大小月及是否闰年,用来确定"日"的数据
        if (list_big.contains(String.valueOf(month + 1))) {
            wv_day.setAdapter(new NumericWheelAdapter(1, 31));
        } else if (list_little.contains(String.valueOf(month + 1))) {
            wv_day.setAdapter(new NumericWheelAdapter(1, 30));
        } else {
            // 闰年
            if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
                wv_day.setAdapter(new NumericWheelAdapter(1, 29));
            else
                wv_day.setAdapter(new NumericWheelAdapter(1, 28));
        }
        wv_day.setLabel("日");
        wv_day.setCurrentItem(day - 1);
 
//        // 时
//        final WheelView wv_hours = (WheelView) view.findViewById(R.id.hour);
//        wv_hours.setAdapter(new NumericWheelAdapter(0, 23));
//        wv_hours.setCyclic(true);
//        wv_hours.setCurrentItem(hour);
//
//        // 分
//        final WheelView wv_mins = (WheelView) view.findViewById(R.id.mins);
//        wv_mins.setAdapter(new NumericWheelAdapter(0, 59, "%02d"));
//        wv_mins.setCyclic(true);
//        wv_mins.setCurrentItem(minute);

        // 添加"年"监听
        OnWheelChangedListener wheelListener_year = new OnWheelChangedListener() {
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                int year_num = newValue + START_YEAR;
                // 判断大小月及是否闰年,用来确定"日"的数据
                if (list_big.contains(String
                        .valueOf(wv_month.getCurrentItem() + 1))) {
                    wv_day.setAdapter(new NumericWheelAdapter(1, 31));
                } else if (list_little.contains(String.valueOf(wv_month
                        .getCurrentItem() + 1))) {
                    wv_day.setAdapter(new NumericWheelAdapter(1, 30));
                } else {
                    if ((year_num % 4 == 0 && year_num % 100 != 0)
                            || year_num % 400 == 0)
                        wv_day.setAdapter(new NumericWheelAdapter(1, 29));
                    else
                        wv_day.setAdapter(new NumericWheelAdapter(1, 28));
                }
            }
        };
        // 添加"月"监听
        OnWheelChangedListener wheelListener_month = new OnWheelChangedListener() {
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                int month_num = newValue + 1;
                // 判断大小月及是否闰年,用来确定"日"的数据
                if (list_big.contains(String.valueOf(month_num))) {
                    wv_day.setAdapter(new NumericWheelAdapter(1, 31));
                } else if (list_little.contains(String.valueOf(month_num))) {
                    wv_day.setAdapter(new NumericWheelAdapter(1, 30));
                } else {
                    if (((wv_year.getCurrentItem() + START_YEAR) % 4 == 0 && (wv_year
                            .getCurrentItem() + START_YEAR) % 100 != 0)
                            || (wv_year.getCurrentItem() + START_YEAR) % 400 == 0)
                        wv_day.setAdapter(new NumericWheelAdapter(1, 29));
                    else
                        wv_day.setAdapter(new NumericWheelAdapter(1, 28));
                }
            }
        };
        wv_year.addChangingListener(wheelListener_year);
        wv_month.addChangingListener(wheelListener_month);

        // 根据屏幕密度来指定选择器字体的大小
        int textSize = 0;

        textSize = 24;
        
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int mDensity = dm.densityDpi;
        
        if (dm.widthPixels >= 320 && dm.widthPixels<480 && dm.heightPixels >= 480 && dm.heightPixels<800) {
            textSize=20;
        }
        if (dm.widthPixels >= 480 && dm.widthPixels <= 720 
                &&dm.heightPixels >= 800 && dm.heightPixels<=1280) {
            textSize=24;
        }
        if (dm.widthPixels >= 720 && dm.heightPixels >= 1280) {
            textSize=32;
        }
        if (dm.widthPixels >= 1000)
        {
            textSize=48;
        }
        
  
        wv_day.TEXT_SIZE = textSize;
 //       wv_hours.TEXT_SIZE = textSize;
 //       wv_mins.TEXT_SIZE = textSize;
        wv_month.TEXT_SIZE = textSize;
        wv_year.TEXT_SIZE = textSize;

        Button btn_sure = (Button) view.findViewById(R.id.btn_datetime_sure);
        Button btn_cancel = (Button) view
                .findViewById(R.id.btn_datetime_cancel);
        // 确定
        btn_sure.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                // 如果是个数,则显示为"02"的样式
                String parten = "00";
                DecimalFormat decimal = new DecimalFormat(parten);
                
                // 设置日期的显示
                // tv_time.setText((wv_year.getCurrentItem() + START_YEAR) + "-"
                // + decimal.format((wv_month.getCurrentItem() + 1)) + "-"
                // + decimal.format((wv_day.getCurrentItem() + 1)) + " "
                // + decimal.format(wv_hours.getCurrentItem()) + ":"
                // + decimal.format(wv_mins.getCurrentItem()));
                
                 edittext.setText((wv_year.getCurrentItem() + START_YEAR) + "-"
                 + decimal.format((wv_month.getCurrentItem() + 1)) + "-"
                 + decimal.format((wv_day.getCurrentItem() + 1)) 
                 );
                 //+ " "
                 //+ decimal.format(wv_hours.getCurrentItem()) + ":"
                 //+ decimal.format(wv_mins.getCurrentItem()));
     
                dialog.dismiss();
            }
        });
        // 取消
        btn_cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
        // 设置dialog的布局,并显示
        dialog.setContentView(view);
        dialog.show();
    
    }
    
    
    
    @JavascriptInterface
    public String getjson() { 
        String json="";
        json= WebServiceUtils.WS_DeptHistorySale_json(
                search_startdate.getText().toString(),
                search_enddate.getText().toString(),
                search_dept_code.getText().toString(),
                search_dept_level.getText().toString(),
                this.showtype
                );
        return json;
    }  
    
    @JavascriptInterface
    public String showtype() {
        return this.showtype;
    }

}
